﻿#if UNITY_EDITOR
using System;
using System.IO;
using UnityEditor;
using UnityEngine;

public class ScreenCaptureEditor : EditorWindow
{
    private static readonly string directory = "Screenshots/Capture/";
    private static string latestScreenshotPath = "";

    private GUIStyle BigText;
    private bool initDone;

    private void OnGUI()
    {
        if (!initDone) InitStyles();

        GUILayout.Label("Screen Capture", BigText);
        if (GUILayout.Button("Take a screenshot")) TakeScreenshot();
        GUILayout.Label("Resolution: " + GetResolution());

        if (GUILayout.Button("Reveal in Explorer")) ShowFolder();
        GUILayout.Label("Directory: " + directory);
    }

    private void InitStyles()
    {
        initDone = true;
        BigText = new GUIStyle(GUI.skin.label)
        {
            fontSize = 20,
            fontStyle = FontStyle.Bold
        };
    }

    [MenuItem("Tools/Screenshots/Open Window")]
    public static void ShowWindow()
    {
        GetWindow(typeof(ScreenCaptureEditor));
    }

    [MenuItem("Tools/Screenshots/Reveal in Explorer")]
    private static void ShowFolder()
    {
        if (File.Exists(latestScreenshotPath))
        {
            EditorUtility.RevealInFinder(latestScreenshotPath);
            return;
        }

        Directory.CreateDirectory(directory);
        EditorUtility.RevealInFinder(directory);
    }

    [MenuItem("Tools/Screenshots/Take a Screenshot")]
    private static void TakeScreenshot()
    {
        Directory.CreateDirectory(directory);
        var currentTime = DateTime.Now;
        var filename = currentTime.ToString().Replace('/', '-').Replace(':', '_') + ".png";
        var path = directory + filename;
        ScreenCapture.CaptureScreenshot(path);
        latestScreenshotPath = path;
        Debug.Log($"Screenshot saved: <b>{path}</b> with resolution <b>{GetResolution()}</b>");
    }

    private static string GetResolution()
    {
        var size = Handles.GetMainGameViewSize();
        var sizeInt = new Vector2Int((int)size.x, (int)size.y);
        return $"{sizeInt.x.ToString()}x{sizeInt.y.ToString()}";
    }
}
#endif